#### Tables S10 and S11: Support for norms/violence by week (panel) ####

# Libraries
#library(tidyverse)
#library(rio)
#library(here)
#library(fixest)
#library(lubridate)

# data_pnas = import(here("Data","data_pnas.rds"))

in_vars = c("norm_judgesre","norm_loyaltyre","norm_pollingre",
            "norm_executivere","norm_censorshipre", paste0("violence",3:6,"re"))

# Identify panel respondents
multi_id = data_pnas |>
  count(uid) |> 
  filter(n > 1) |> 
  pull(uid)

data_multi = filter(data_pnas, uid %in% multi_id) |> 
  select(uid, week_since, all_of(in_vars), weight, wt_adj) |> 
  group_by(uid) |> 
  mutate(interview = rank(week_since, na.last = NA),
         weight = weight * wt_adj) |> # remove weight correction for cross-sectional analysis 
  arrange(uid, interview) 

## Panel Regressions 
panel_reg = \(x){
  # Run regressions
  mod_stability = feols(fml = as.formula(paste0(x," ~ week_since | uid")),
                        data = data_multi, weights = data_multi$weight)
  #Output dataframe
  lst_stability = lst(type = "stability",
                      depvar = x,
                      mod = mod_stability)
  lst(lst_stability)
}

panel_out = map(in_vars, ~ panel_reg(.x))
names(panel_out) = in_vars

etab_create = \(out, vars, type, file){
  xtrct = map(vars, \(y){
    out[[y]][[type]][["mod"]]
  })
  etable(xtrct, digits = 2, file = file, replace = T,
         signif.code = c("***"=0.001, "**"=0.01, "*"=0.05))
}

etab_create(panel_out,
            c("norm_judgesre","norm_loyaltyre","norm_pollingre",
              "norm_executivere","norm_censorshipre"),
            "lst_stability", here("Tables","Supplementary","table_s10.tex")) 

etab_create(panel_out,
            c(paste0("violence",3:6,"re")),
            "lst_stability", here("Tables","Supplementary","table_s11.tex"))